<?php

namespace App\Listeners;

use App\Constant;
use App\Events\OrderComplete;
use App\Events\RechargeComplete;
use App\Models\BalanceLogModel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class RebateOrder
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\OrderComplete  $event
     * @return void
     */
    public function handle(OrderComplete $event)
    {
        //
        $order_model = $event->order;
        $detail_list = $order_model->orderDetails;
        foreach ($detail_list as $k => $v) {
            $seller_model = $v->seller;
            $real_product = $v->product;
            $raw_product = $v->product->referrel;
            if(!$raw_product) {
                Log::error("{$order_model->id}#{$v->id}#无源头商品");
            }
            $money = $real_product->unit_price - ($raw_product ? $raw_product->unit_price : 0);
            Log::error("{$order_model->id}#{$v->id}#{$money}");
            if($money > 0) {
                BalanceLogModel::create([
                    'user_id' => $seller_model->id,
                    'type' => Constant::BALANCE_LOG_TYPE_ORDER_REBATE,
                    'value_before' => $seller_model->balance,
                    'value' => $money,
                    'description' => "Order Profit",
                    'trade_id' => $v->id,
                ]);
                $seller_model->balance += $money;
                $seller_model->save();
            }
        }


    }
}
